"""定义一个方法将cookie数据添加到redis中"""

import pickle,base64

from django_redis import get_redis_connection


def merge_cookie_to_redis(request,response):
    """未登录用户登录后合并购物车"""
    # 读取cookie
    carts_cookies = request.COOKIES.get('carts')
    if carts_cookies:
        carts = pickle.loads(base64.b64decode(carts_cookies))
        # 初始化cookie数据
        sku_id_count = {}
        selected_ids = []
        unselected_ids = []
        # 查询redis
        for sku_id,count_dict in carts.items():
            sku_id_count[sku_id] = count_dict['count']
            if count_dict['selected']:
                selected_ids.append(sku_id)
            else:
                unselected_ids.append(sku_id)

        user = request.user
        redis_cli = get_redis_connection('carts')
        pipeline =redis_cli.pipeline()
        pipeline.hmset('carts_%s'%user.id,sku_id_count)
        if len(selected_ids)>0:
            # 解包
            pipeline.sadd('selected_%s'%user.id,*selected_ids)
        if len(unselected_ids)>0:

            pipeline.srem('selected_%s'%user.id,*unselected_ids)

        pipeline.execute()

    return response